package com.atguigu.tingshu.gateway.filter;

import com.atguigu.tingshu.common.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 * 全局Filter，统一处理会员登录与外部不允许访问的服务
 * 从请求头中获取 token，从 Redis 中获取用户 ID，并添加到请求头传递给下游服务
 * </p>
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 从请求头中获取 token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        // 2. 如果 token 存在，从 Redis 中获取用户 ID
        if (StringUtils.hasText(token)) {
            String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            String userIdStr = redisTemplate.opsForValue().get(loginKey);
            // 3. 如果用户 ID 存在，添加到请求头中传递给下游服务
            if (StringUtils.hasText(userIdStr)) {
                // 使用 mutate() 方法修改请求，添加 userId 请求头
                ServerHttpRequest request = exchange.getRequest().mutate()
                        .header("userId", userIdStr)
                        .build();
                // 使用修改后的请求创建新的 exchange
                exchange = exchange.mutate().request(request).build();
                log.debug("网关添加用户ID到请求头 - userId: {}", userIdStr);
            }
        }

        // 4. 放行请求
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
